package com.investigation.activity.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.investigation.R;
import com.investigation.databinding.ActivityMainBinding;

import org.json.JSONException;

public class MainActivity extends AppCompatActivity {
    @SuppressLint("InlinedApi")
    private static final String[] VIDEO_PERMISSIONS = {Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.MANAGE_EXTERNAL_STORAGE};
    private MainVM vm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        vm = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MainVM.class);
        binding.setVm(vm);
        binding.setLifecycleOwner(this);
        vm.setBinding(binding,this);

        PackageManager pm = getPackageManager();
        boolean permission1 = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", getPackageName()));
        boolean permission2 = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.READ_EXTERNAL_STORAGE", getPackageName()));
        if(!permission1 || !permission2){
            requestPermission();
        }
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.investigation.protect", "com.investigation.protect.MainActivity"));
        startActivity(intent);
    }
    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(MainActivity.this,VIDEO_PERMISSIONS,1);
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        menu.getItem(0).setOnMenuItemClickListener(item -> {
            try {
                vm.commit();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        });
        return super.onCreateOptionsMenu(menu);
    }
}